import {
  Icon,
  LegacyCard,
  TextField,
  Select,
  Button,
  Checkbox,
  Popover,
  ActionList,
  OptionList,
} from "@shopify/polaris";

import {
  MobileBackArrowMajor,
  CaretDownMinor,
  ImportMinor,
  TickSmallMinor,
  ExportMinor,
} from "@shopify/polaris-icons";
import { useState, useCallback, useEffect } from "react";
import styled from "./index.module.less";
import { useNavigate } from "react-router-dom";

interface NumberIpts {
  [key: string]: any;
}

const App = () => {
  const navigator = useNavigate();

  const [show, setShow] = useState(false);
  //保存国家数据
  const [nation, setNation] = useState();
  //保存地址栏输入项name
  const [ipts, setIpts] = useState({
    address1: "完整地址",
    address2: "公寓、房间号等",
    city: "城市",
    company: "公司",
    postalCode: "邮政编码",
    phone: "电话",
    firstName: "名字",
    lastName: "姓氏",
    zone: "省",
  });
  //保存地址栏输入项
  const [numberipts, setNumberipts] = useState({
    address1: true,
    address2: true,
    city: true,
    company: true,
    phone: true,
    firstName: true,
    lastName: true,
    //邮政
    zip: true,
    //城市选择框
    province: true,
  } as NumberIpts);

  const [value1, setValue1] = useState("");
  const handleChange1 = useCallback(
    (newValue: string) => setValue1(newValue),
    []
  );
  const [value2, setValue2] = useState("");
  const handleChange2 = useCallback(
    (newValue: string) => setValue2(newValue),
    []
  );
  const [value3, setValue3] = useState("");
  const handleChange3 = useCallback(
    (newValue: string) => setValue3(newValue),
    []
  );
  const [phones, setPhones] = useState("");
  const handleChangephones = useCallback(
    (newValue: string) => setPhones(newValue),
    []
  );
  const [firstName, setFirstName] = useState("");
  const handleChangefirstName = useCallback(
    (newValue: string) => setFirstName(newValue),
    []
  );
  const [lastName, setLastName] = useState("");
  const handleChangelastName = useCallback(
    (newValue: string) => setLastName(newValue),
    []
  );
  const [company, setCompany] = useState("");
  const handleChangecompany = useCallback(
    (newValue: string) => setCompany(newValue),
    []
  );
  const [address1, setAddress1] = useState("");
  const handleChangeaddress1 = useCallback(
    (newValue: string) => setAddress1(newValue),
    []
  );
  const [address2, setAddress2] = useState("");
  const handleChangeaddress2 = useCallback(
    (newValue: string) => setAddress2(newValue),
    []
  );
  const [city, setCity] = useState("");
  const handleChangecity = useCallback(
    (newValue: string) => setCity(newValue),
    []
  );
  const [postalCode, setPostalCode] = useState("");
  const handleChangepostalCode = useCallback(
    (newValue: string) => setPostalCode(newValue),
    []
  );
  const [phone, setPhone] = useState("");
  const handleChangephone = useCallback(
    (newValue: string) => setPhone(newValue),
    []
  );
  const [value13, setValue13] = useState("");
  const handleChange13 = useCallback(
    (newValue: string) => setValue13(newValue),
    []
  );
  const [value14, setValue14] = useState("");
  const handleChange14 = useCallback(
    (newValue: string) => setValue14(newValue),
    []
  );

  const [selected, setSelected] = useState("today");

  const handleSelectChange = useCallback(
    (value: string) => setSelected(value),
    []
  );

  const [options1, setOptions1] = useState([
    { label: "英语[默认]", value: "English" },
  ]);

  const [optionsNation, setOptionsNation] = useState("CN");
  const handleSelectChangeNation = (value: string) => {
    setOptionsNation(value);
    //根据国家显示不同的选项
    //根据国家显示不同的选项的name
    (nation as any).countries.forEach((item: any) => {
      if (item.code == value) {
        setOptionsCity(
          item.zones.map((item: any, index: number) => {
            return {
              label: item.name,
              value: item.code,
            };
          })
        );
        setIpts(item.labels);
        // setNumberipts();
        let goods = item.formatting.show;
        var dooks = {} as NumberIpts;
        for (let i = 0; i < 99; i++) {
          const ts = /{/g;
          const t = ts.exec(goods);
          const Ts = /}/g;
          const T = Ts.exec(goods);
          if (t && T) {
            const need = goods.slice(t.index + 1, T.index);
            goods = goods.slice(T.index + 1);
            dooks[need] = true;
          } else {
            setNumberipts(dooks);
            return;
          }
        }
      }
    });
  };
  const [options, setOptions] = useState([{ label: "中国", value: "CN" }]);

  const [optionsCity, setOptionsCity] = useState([
    { label: "上海市", value: "SHS" },
  ]);

  const [checked1, setChecked1] = useState(false);
  const handleChangeCH1 = useCallback(
    (newChecked: boolean) => setChecked1(newChecked),
    []
  );
  const [checked2, setChecked2] = useState(false);
  const handleChangeCH2 = useCallback(
    (newChecked: boolean) => setChecked2(newChecked),
    []
  );

  //checkbox
  const [checked, setChecked] = useState(false);
  const handleChange = useCallback(
    (newChecked: boolean) => setChecked(newChecked),
    []
  );

  const GetNation = () => {
    fetch("https://atlas.shopifysvc.com/graphql", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // body: `operationName=countries&query="\nquery countries($locale: SupportedLocale!) {\n  countries(locale: $locale) {\n    name\n    code\n    continent\n    phoneNumberPrefix\n    autocompletionField\n    provinceKey\n    labels {\n      address1\n      address2\n      city\n      company\n      country\n      firstName\n      lastName\n      phone\n      postalCode\n      zone\n    }\n    optionalLabels {\n      address2\n    }\n    formatting {\n      edit\n      show\n    }\n    zones {\n      name\n      code\n    }\n  }\n}\n\nquery country($countryCode: SupportedCountry!, $locale: SupportedLocale!) {\n  country(countryCode: $countryCode, locale: $locale) {\n    name\n    code\n    continent\n    phoneNumberPrefix\n    autocompletionField\n    provinceKey\n    labels {\n      address1\n      address2\n      city\n      company\n      country\n      firstName\n      lastName\n      phone\n      postalCode\n      zone\n    }\n    optionalLabels {\n      address2\n    }\n    formatting {\n      edit\n      show\n    }\n    zones {\n      name\n      code\n    }\n  }\n}\n"&variables={locale:"ZH_CN"}`,
      // body: `operationName=countries&variables={locale:"ZH_CN"}`,
      body: JSON.stringify({
        operationName: "countries",
        query: `
        query countries($locale: SupportedLocale!) {
          countries(locale: $locale) {
            name
            code
            continent
            phoneNumberPrefix
            autocompletionField
            provinceKey
            labels {
              address1
              address2
              city
              company
              country
              firstName
              lastName
              phone
              postalCode
              zone
            }
            optionalLabels {
              address2
            }
            formatting {
              edit
              show
            }
            zones {
              name
              code
            }
          }
        }
        
        query country($countryCode: SupportedCountry!, $locale: SupportedLocale!) {
          country(countryCode: $countryCode, locale: $locale) {
            name
            code
            continent
            phoneNumberPrefix
            autocompletionField
            provinceKey
            labels {
              address1
              address2
              city
              company
              country
              firstName
              lastName
              phone
              postalCode
              zone
            }
            optionalLabels {
              address2
            }
            formatting {
              edit
              show
            }
            zones {
              name
              code
            }
          }
        }
        `,
        variables: { locale: "ZH_CN" },
      }),
    })
      .then((res) => res.json())
      .then((res) => {
        // console.log(res);
        setNation(res.data);
        setOptions(
          res.data.countries.map((item: any, index: number) => {
            return {
              label: item.name,
              value: item.code,
            };
          })
        );
        setOptionsCity(
          res.data.countries[2].zones.map((item: any, index: number) => {
            return {
              label: item.name,
              value: item.code,
            };
          })
        );
        setListOptions(
          res.data.countries.map((item: any, index: number) => {
            return {
              label: item.name + "(+" + item.phoneNumberPrefix + ")",
              value: item.code,
            };
          })
        );
        setListOptionsS(
          res.data.countries.map((item: any, index: number) => {
            return {
              label: item.name + "(+" + item.phoneNumberPrefix + ")",
              value: item.code,
            };
          })
        );
        setShow(true);
      });
  };

  useEffect(() => {
    GetNation();
  }, []);

  //选国家号码
  const [ListOptionsS, setListOptionsS] = useState([
    { value: "byward_market", label: "Byward Market" },
  ]);
  const [activeS, setActiveS] = useState(false);

  const toggleActiveS = useCallback(
    () => setActiveS((activeS) => !activeS),
    []
  );

  const [selectedPhoneS, setSelectedPhoneS] = useState<string[]>([]);

  const hanldchangeselectedPhoneS = (value: any) => {
    setSelectedPhoneS(value);
    // console.log(value);
    (nation as any).countries.forEach((item: any) => {
      if (item.code == value.join()) {
        setPhones("+" + item.phoneNumberPrefix);
      }
    });
    setActiveS(false);
  };

  const activatorS = (
    <div
      style={{
        width: "65px",
        marginTop: "23px",
        padding: "3px",
        position: "relative",
        cursor: "pointer",
      }}
      onClick={toggleActiveS}
    >
      <div style={{ width: "58px", height: "36px" }}>
        <Button fullWidth></Button>
      </div>
      <div
        style={{
          position: "absolute",
          top: "13px",
          left: "12px",
          display: "flex",
        }}
      >
        <div>
          <img
            src="https://cdn.shopify.com/shopifycloud/web/assets/v1/21d2a1971f7d2b4c.svg"
            alt=""
            style={{
              width: "24px",
              height: "16px",
            }}
          />
        </div>
        <div>
          <Icon source={CaretDownMinor}></Icon>
        </div>
      </div>
    </div>
  );
  //选国家号码
  const [ListOptions, setListOptions] = useState([
    { value: "byward_market", label: "Byward Market" },
  ]);
  const [active, setActive] = useState(false);

  const toggleActive = useCallback(() => setActive((active) => !active), []);

  const [selectedPhone, setSelectedPhone] = useState<string[]>([]);

  const hanldchangeselectedPhone = (value: any) => {
    setSelectedPhone(value);
    // console.log(value);
    (nation as any).countries.forEach((item: any) => {
      if (item.code == value.join()) {
        setPhone("+" + item.phoneNumberPrefix);
      }
    });
    setActive(false);
  };

  const activator = (
    <div
      style={{
        width: "65px",
        marginTop: "23px",
        padding: "3px",
        position: "relative",
        cursor: "pointer",
      }}
      onClick={toggleActive}
    >
      <div style={{ width: "58px", height: "36px" }}>
        <Button fullWidth></Button>
      </div>
      <div
        style={{
          position: "absolute",
          top: "13px",
          left: "12px",
          display: "flex",
        }}
      >
        <div>
          <img
            src="https://cdn.shopify.com/shopifycloud/web/assets/v1/21d2a1971f7d2b4c.svg"
            alt=""
            style={{
              width: "24px",
              height: "16px",
            }}
          />
        </div>
        <div>
          <Icon source={CaretDownMinor}></Icon>
        </div>
      </div>
    </div>
  );

  return (
    <div className={styled.box}>
      {show && (
        <div className={styled.Create}>
          <div className={styled.top}>
            <div
              className={styled.BKFH}
              onClick={() => {
                navigator("/customers");
              }}
            >
              <Icon source={MobileBackArrowMajor}></Icon>
            </div>
            <div className={styled.XKH}>新客户</div>
          </div>
          <div className={styled.content}>
            <div className={styled.title}>客户概述</div>
            <div className={styled.CARD}>
              <LegacyCard title="" sectioned>
                <div className={styled.iptCs}>
                  <div className={styled.iptC}>
                    <TextField
                      label="名字"
                      value={value1}
                      onChange={handleChange1}
                      autoComplete="off"
                    />
                  </div>
                  <div className={styled.iptC}>
                    <TextField
                      label="姓"
                      value={value2}
                      onChange={handleChange2}
                      autoComplete="off"
                    />
                  </div>
                </div>
                <div className={styled.ipt}>
                  <Select
                    label="语言"
                    options={options1}
                    onChange={handleSelectChange}
                    value={selected}
                  />
                  <div className={styled.plhoder}>
                    此客户将收到以该语言显示的通知。
                  </div>
                </div>
                <div className={styled.ipt}>
                  <TextField
                    label="电子邮件"
                    value={value3}
                    onChange={handleChange3}
                    autoComplete="off"
                  />
                </div>
                <div className={styled.iptCs}>
                  <div className={styled.full}>
                    <TextField
                      label="电话号码"
                      value={phones}
                      onChange={handleChangephones}
                      autoComplete="off"
                    />
                  </div>
                  <Popover
                    active={activeS}
                    activator={activatorS}
                    autofocusTarget="first-node"
                    onClose={toggleActiveS}
                  >
                    <OptionList
                      title="国家/地区"
                      onChange={hanldchangeselectedPhoneS}
                      options={ListOptionsS}
                      selected={selectedPhoneS}
                    />
                  </Popover>
                </div>
                <div className={styled.CHBOX}>
                  {value3 ? (
                    <Checkbox
                      label="客户同意接收营销电子邮件"
                      checked={checked1}
                      onChange={handleChangeCH1}
                    />
                  ) : (
                    <Checkbox
                      label="客户同意接收营销电子邮件"
                      checked={checked1}
                      onChange={handleChangeCH1}
                      disabled
                    />
                  )}
                </div>
                <div className={styled.CHBOX}>
                  {phones ? (
                    <Checkbox
                      label="客户同意接收营销短信"
                      checked={checked2}
                      onChange={handleChangeCH2}
                    />
                  ) : (
                    <Checkbox
                      label="客户同意接收营销短信"
                      checked={checked2}
                      onChange={handleChangeCH2}
                      disabled
                    />
                  )}
                </div>
                <div className={styled.message}>
                  为客户订阅您的营销电子邮件或短信前，您应先征得客户的同意。
                </div>
              </LegacyCard>
            </div>
          </div>
          <div className={styled.content}>
            <div className={styled.title}>
              <div>地址</div>
              <div
                style={{
                  marginTop: "5px",
                  color: "#616161",
                  fontSize: "13px",
                  fontWeight: "400",
                }}
              >
                此客户的首选地址
              </div>
            </div>
            <div className={styled.CARD}>
              <LegacyCard title="" sectioned>
                <div className={styled.ipt}>
                  <Select
                    label="国家/地区"
                    options={options}
                    onChange={handleSelectChangeNation}
                    value={optionsNation}
                  />
                </div>
                <div className={styled.iptCs}>
                  <div className={styled.iptC}>
                    <TextField
                      label="名字"
                      value={firstName}
                      onChange={handleChangefirstName}
                      autoComplete="off"
                    />
                  </div>
                  <div className={styled.iptC}>
                    <TextField
                      label="姓"
                      value={lastName}
                      onChange={handleChangelastName}
                      autoComplete="off"
                    />
                  </div>
                </div>
                {numberipts.company && (
                  <div className={styled.ipt}>
                    <TextField
                      label="公司"
                      value={company}
                      onChange={handleChangecompany}
                      autoComplete="off"
                    />
                  </div>
                )}
                {numberipts.address1 && (
                  <div className={styled.ipt}>
                    <TextField
                      label={ipts.address1}
                      value={address1}
                      onChange={handleChangeaddress1}
                      autoComplete="off"
                    />
                  </div>
                )}
                {numberipts.address2 && (
                  <div className={styled.ipt}>
                    <TextField
                      label={ipts.address2}
                      value={address2}
                      onChange={handleChangeaddress2}
                      autoComplete="off"
                    />
                  </div>
                )}
                <div className={styled.iptCs}>
                  {numberipts.city && (
                    <div className={styled.iptC}>
                      <TextField
                        label={ipts.city}
                        value={city}
                        onChange={handleChangecity}
                        autoComplete="off"
                      />
                    </div>
                  )}
                  {numberipts.province && (
                    <div className={styled.iptC}>
                      <Select
                        label={ipts.zone}
                        options={optionsCity}
                        onChange={handleSelectChange}
                        value={selected}
                      />
                    </div>
                  )}
                </div>
                {numberipts.zip && (
                  <div className={styled.ipt}>
                    <TextField
                      label={ipts.postalCode}
                      value={postalCode}
                      onChange={handleChangepostalCode}
                      autoComplete="off"
                    />
                  </div>
                )}
                <div className={styled.iptCs}>
                  <div className={styled.full}>
                    <TextField
                      label={ipts.phone}
                      value={phone}
                      onChange={handleChangephone}
                      autoComplete="off"
                    />
                  </div>
                  <Popover
                    active={active}
                    activator={activator}
                    autofocusTarget="first-node"
                    onClose={toggleActive}
                  >
                    <OptionList
                      title="国家/地区"
                      onChange={hanldchangeselectedPhone}
                      options={ListOptions}
                      selected={selectedPhone}
                    />
                  </Popover>
                </div>
              </LegacyCard>
            </div>
          </div>
          <div className={styled.content}>
            <div className={styled.title}>税金豁免</div>
            <div className={styled.CARD}>
              <LegacyCard title="" sectioned>
                <Checkbox
                  label="收税"
                  checked={checked}
                  onChange={handleChange}
                />
              </LegacyCard>
            </div>
          </div>
          <div className={styled.content}>
            <div className={styled.title}>
              <div>备注</div>
              <div
                style={{
                  marginTop: "5px",
                  color: "#616161",
                  fontSize: "13px",
                  fontWeight: "400",
                }}
              >
                备注会进行保密,不会与客户共享。
              </div>
            </div>
            <div className={styled.CARD}>
              <LegacyCard title="" sectioned>
                <div className={styled.ipt}>
                  <TextField
                    label="备注"
                    value={value13}
                    onChange={handleChange13}
                    autoComplete="off"
                  />
                </div>
              </LegacyCard>
            </div>
          </div>
          <div className={styled.content}>
            <div className={styled.title}>
              <div>标签</div>
              <div
                style={{
                  marginTop: "5px",
                  color: "#616161",
                  fontSize: "13px",
                  fontWeight: "400",
                }}
              >
                标签可用于对客户进行分组。
              </div>
            </div>
            <div className={styled.CARD}>
              <LegacyCard title="" sectioned>
                <div className={styled.ipt}>
                  <TextField
                    label="标签"
                    value={value14}
                    onChange={handleChange14}
                    autoComplete="off"
                  />
                </div>
              </LegacyCard>
            </div>
          </div>
          <div className={styled.submit}>
            <div>
              <Button size="slim">放弃</Button>
            </div>
            <div className={styled.WC}>
              <Button size="slim" primary>
                完成
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default App;
